﻿@using System.Web.Script.Serialization;
@{
  //  ViewBag.Title = "AppointmentDetail";
  if (Session["Clinic"] != null)
    {
        HMS.Web.Helpers.Clinic clinic = new HMS.Web.Helpers.Clinic();
        clinic = (HMS.Web.Helpers.Clinic)Session["Clinic"];
        ViewBag.Title = clinic.Name;
    }
    else
  {
      ViewBag.Title = "AppointmentDetail";
  }
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@model List<HMS.Web.Helpers.DailyViewModel>

<section class="container appointment-detail">
    <div class="page-heading pull-left col-lg-12 col-md-12 col-xs-12">
        <hr class="pull-left col-lg-12 col-md-12 col-xs-12 clear-padding" />
        <h1 class="pull-left col-lg-8 col-md-12 col-xs-12 clear-padding">Appointment Details</h1>
        <button id="newAppointment" class="btn btn-primary newAppointment" style="">New Appointment</button>
        <button id="sendNotification" class="btn btn-primary other-header-field sendNotification">Send Notification</button>
        <hr class="pull-left col-lg-12 col-md-12 col-xs-12 clear-padding" />

    </div>
    <div id="selectedDate">
        @if (Model != null && Model.Count > 0)
        {
            <h2 class="text-center"> @Model[0].AppointmentTime.Date.ToString("ddd, MMM d, yyyy")</h2>
        }
    </div>
    
    <div class="container-fluid" id="apptGrid">
        @if (Model != null && Model.Count > 0)
        {
            <i class="note-bit">Note : The sections in grey are blocked due to unavailability of the doctor.</i>
            <div class="row btn-primary">
                <div class="col-md-2 col-sm-2 col-xs-2 col text-center"><span class="glyphicon glyphicon-time"></span></div>
                <div class="col-md-10 col-sm-10 col-xs-7 col text-center">Patient Details</div>
            </div>
    <div class="row dhx_scale_holder time col-lg-2 col-sm-2 col-md-2 col-xs-4 text-center pull-left" style="height:100%">
        <div class="row time-division"><div class="dhx_scale_hour">08:00 AM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">09:00 AM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">10:00 AM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">11:00 AM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">12:00 PM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">01:00 PM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">02:00 PM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">03:00 PM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">04:00 PM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">05:00 PM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">06:00 PM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">07:00 PM<span class="time-separetor pull-right">---</span></div></div>
        <div class="row time-division"><div class="dhx_scale_hour">08:00 PM<span class="time-separetor pull-right">---</span></div></div>
    </div>
            <div class="dhx_scale_holder slot col-lg-10 col-sm-10 col-md-10 col-xs-9 text-center pull-left" style="height:100%">
                <div class="time-division slot-division"><div class="message" id="08_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="08_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="09_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="09_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="10_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="10_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="11_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="11_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="12_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="12_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="13_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="13_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="14_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="14_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="15_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="15_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="16_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="16_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="17_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="17_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="18_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="18_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="19_00"></div></div>
                <div class="time-division slot-division"><div class="message" id="19_30"></div></div>
                <div class="time-division slot-division"><div class="message" id="20_00"></div></div>
            </div>
            
            <h2 class="text-center" id="emptyGrid"> </h2>
        }
        else
        {
            HMS.Web.Helpers.DoctorSession docSession = (HMS.Web.Helpers.DoctorSession)Session["DoctorDetails"];
            <h2 class="text-center" id="emptyGrid"> No Appointments are scheduled for @docSession.date.ToString("dd-MMM-yyyy")</h2>
        }

    </div>
    <br />
    <br />
    <br />
</section>
<script type="text/javascript" src="~/Scripts/responsive-calendar.js"></script>
@*<script type="text/javascript" src="~/Scripts/appt_Details.js"></script>*@
<script type="text/javascript" src="~/Scripts/common.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#newAppointment").click(function () {
            $.ajax({
                type: "POST",
                url: _AbsolutePath + 'Appointment/NewDocAppt',
                contentType: "application/json",
                data: null,
                caller: arguments.callee.name,//gets currently running function name
                dataType: "json", //Cross domain call (even json also work)
                success: function (res) {
                    location.href = _AbsolutePath + 'Appointment/EditAppointment';
                },
                error: function (xhr) {
                }
            });
        });
        var modelObj = JSON.parse('@Html.Raw(new JavaScriptSerializer().Serialize(Model))')
        var modelData = JSON.parse('@Html.Raw(new JavaScriptSerializer().Serialize(Model))')
        $("a.tooltipgrid").tooltip();
        $("#sendNotification").click(function () {
            if (modelData.length > 0) {
                docPersonalDet = JSON.parse(localStorage.getItem("DocPersonalDet"));

                //$.each(modelData, function (index, item) {
                //    if (environment == "prod")
                //        var _apptdateTime = item.AppointmentTime.replace('(', '').replace(')', '').split('/')[1] + "/" + item.AppointmentTime.replace('(', '').replace(')', '').split('/')[0] + "/" + item.AppointmentTime.replace('(', '').replace(')', '').split('/')[2];
                //    else
                //        var _apptdateTime = item.AppointmentTime.replace('(', '').replace(')', '').split('/')[0] + "/" + item.AppointmentTime.replace('(', '').replace(')', '').split('/')[1] + "/" + item.AppointmentTime.replace('(', '').replace(')', '').split('/')[2];
                //    modelData[index].AppointmentDateTime = _apptdateTime.substring(0, 16) + " " + _apptdateTime.substring(17, 19);;
                //});

                $.ajax({
                    type: "POST",
                    async:true,
                    url: _AbsolutePath + 'Appointment/SendNotification',
                    contentType: "application/json",
                    data: JSON.stringify({ dailyViewModelList: modelData, doctorName: docPersonalDet.DoctorName }),
                    caller: arguments.callee.name,//gets currently running function name
                    dataType: "json", //Cross domain call (even json also work)
                    success: function () {
                        //alert("Notification sent");
                    },
                    error: function (xhr) {
                    }
                });
                alert("Notifications will be sent");
            }
        });

        _.each(modelObj, function (item) {
            var apptTime = item._ApptTime;
            var time = apptTime.split(':');
            //var apptTime = (new Date(parseInt(item.AppointmentTime.replace("/Date(", "").replace(")/", ""))));
            //var time = apptTime.toTimeString().split(' ')[0].split(':');
            var status = parseInt(item.ApptStatusId) == 2 ? "approved" : "completed";
            var followUp = item.IsFollowUp ? '<span class="col-lg-1 col-md-1 cold-xs-1 glyphicon glyphicon-retweet"></span>' : '<span class="col-lg-1 col-md-1 cold-xs-1"></span>';
            $("#" + time[0] + "_" + time[1]).parent().addClass(status);
            if ($("#" + time[0] + "_" + time[1]).html()) {
                var newElement = '';
                if ($('.' + time[0] + "_" + time[1]).length) newElement = $('.' + time[0] + "_" + time[1]);
                else newElement = $('<div/>');                
                if (status == "approved")
                    newElement.html(newElement.html() + '<div class="time-division slot-division approved"><div class="message"><a href="tel:' + item.Phone + '" class="fa fa-phone col-lg-1 col-xs-1 col-sm-1"></a>  <a href="tel:' + item.Phone + '"><span>' + item.Name.substr(0,7) + '</span></a>' + followUp + '<span class="pointer pull-right fa fa-close col-lg-2  col-sm-1 col-xs-2" onclick="DeleteAppointment(' + item.Id + ',this)"></span><span class="pointer pull-right fa fa-edit col-lg-2 col-xs-2" onclick="EditAppointment(' + item.Id + ',' + item.PatientId + ')"></span></div></div>');
                else
                    newElement.html(newElement.html() + '<div class="time-division slot-division approved"><div class="message"><a href="tel:' + item.Phone + '" class="fa fa-phone col-lg-1 col-xs-1 col-sm-1"></a>  <a href="tel:' + item.Phone + '"><span>' + item.Name.substr(0, 7) + '</span></a>' + followUp + '</div></div>');

                newElement.addClass(time[0] + "_" + time[1]);
                if (!$('.' + time[0] + "_" + time[1]).length) {
                    $('body').append(newElement);
                    $("#" + time[0] + "_" + time[1]).html($("#" + time[0] + "_" + time[1]).html() + '<span class="pull-right"><div class="pointer more-link" onclick="showMoreAppts(\'' + time[0] + '_' + time[1] + '\')">check more</div></span>')
                }
            }
            else {
                if (status == "approved")
                    $("#" + time[0] + "_" + time[1]).html('<a href="tel:' + item.Phone + '" class="fa fa-phone col-lg-1 col-xs-1 col-sm-1"></a>  <a href="tel:' + item.Phone + '"><span>' + item.Name.substr(0, 7) + '</span></a>' + followUp + '<span class="pointer pull-right fa fa-close col-lg-2  col-sm-1 col-xs-2" onclick="DeleteAppointment(' + item.Id + ',this)"></span><span class="pointer pull-right fa fa-edit col-lg-2 col-xs-2" onclick="EditAppointment(' + item.Id + ',' + item.PatientId + ')"></span>')
                else
                    $("#" + time[0] + "_" + time[1]).html('<a href="tel:' + item.Phone + '" class="fa fa-phone col-lg-1 col-xs-1 col-sm-1"></a> <a href="tel:' + item.Phone + '"><span>' + item.Name.substr(0, 7) + '</span></a>' + followUp + '')
            }
        });
        _.each($(".message"), function (item) { if (item.innerHTML === "") $("#" + item.getAttribute("id")).removeClass("message").parent().addClass("no-message") });
        $("body > div").dialog({
            autoOpen: false,
            title: "Patient Details"
        });



        var DocInfo = JSON.parse(localStorage.getItem("DoctorInfo"));
        if (environment == "prod") {
            localStorage.getItem("selectedDate")
        } else {

        }
        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Appointment/GetDoctorSlots',
            contentType: "application/json",
            data: JSON.stringify({ DocId: parseInt(DocInfo.DocId) }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                _.each(res, function (item) {
                    $("#" + item.replace(':', '_')).parent().addClass("unavailable-slot").removeClass("no-message");
                });

            },
            error: function (xhr) {
                //alert(1);
                //location.href = "/Appointment/AppointmentDetails
            }
        });

    });
    function EditAppointment(_appointmentId, patientId) {
        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Appointment/AddDocApptIdToSession',
            contentType: "application/json",
            data: JSON.stringify({ DoctorApptId: _appointmentId, patientId: patientId }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                location.href = _AbsolutePath + 'Appointment/EditAppointment';
            },
            error: function (xhr) {
            }
        });
    }

    function DeleteAppointment(_appointmentId, element) {
        if (confirm("Do you want to delete this appointment?")) {
            $.ajax({
                type: "POST",
                url: _AbsolutePath + 'Appointment/DeleteAppointment',
                contentType: "application/json",
                data: JSON.stringify({ DocAppId: _appointmentId }),
                caller: arguments.callee.name,//gets currently running function name
                dataType: "json", //Cross domain call (even json also work)
                success: function (res) {
                    var rowToDelete = $(element).closest(".message");
                    var isMoreAppAvl = rowToDelete.find(".more-link");
                    rowToDelete.html("")
                    rowToDelete.removeClass("message").parent().addClass("no-message");
                    if ($(".time-division.slot-division .message").length == 0) {
                        $(".row.btn-primary,.dhx_scale_holder,#selectedDate").remove();
                        $("#emptyGrid").html("No Appointments are scheduled for this date.");
                    }
                    SendNotificationForDeletedAppointment(res);
                    if (isMoreAppAvl) window.location.reload();
                },
                error: function (xhr) {

                }
            });
        }
    }


    function SendNotificationForDeletedAppointment(DocApptId) {
        $.ajax({
            async: true,
            type: "POST",
            url: _AbsolutePath + 'Appointment/SendEmailforAppointmentDeleted',
            contentType: "application/json",
            data: JSON.stringify({ docAppt: DocApptId }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {

            },
            error: function (xhr) {
            }
        });
    }
    
    function showMoreAppts(time) {
        $('.ui-dialog > div.' + time).dialog('open');
        $('.ui-dialog.ui-widget.ui-widget-content.ui-corner-all.ui-front.ui-draggable.ui-resizable').css('width', '500px');
    
    }
</script>